﻿using Microsoft.Extensions.Configuration;
using Microsoft.Extensions.DependencyInjection;
using Quartz;

namespace Byte.Core.Common.Extensions
{
    public static class QuartzExtensions
    {
        public static void AddJobAndTrigger<T>(
        this IServiceCollection quartz,
        IConfiguration config)
        where T : IJob
        {
            // Use the name of the IJob as the appsettings.json key
            string jobName = typeof(T).Name;

            // Try and load the schedule from configuration
            var configKey = $"Quartz:{jobName}";
            var cronSchedule = config[configKey];

            // Some minor validation
            if (string.IsNullOrEmpty(cronSchedule))
            {
                throw new Exception($"No Quartz.NET Cron schedule found for job in configuration at {configKey}");
            }

            //var trigger1 = TriggerBuilder.Create()
            //            // .WithSimpleSchedule(x => x.WithIntervalInSeconds(2).RepeatForever())//每两秒执行一次 执行3次
            //            .WithSimpleSchedule(x => x.WithIntervalInSeconds(2).WithRepeatCount(0))//每两秒执行一次 执行3次
            //            .Build();
            ////4、创建任务
            //var job1 = JobBuilder.Create<MyJob>()
            //                .WithIdentity("job1", "group1")
            //                .Build();




            // register the job as before
            //var jobKey = new JobKey(jobName);
            //quartz.AddJob<T>(opts => opts.WithIdentity(jobKey));

            //quartz.AddTrigger(opts => opts
            //    .ForJob(jobKey)
            //    .WithIdentity(jobName + "-trigger")
            //    .WithCronSchedule(cronSchedule)); // use the schedule from configuration
        }
    }
}

